﻿using System.Linq;
using System.Web.Mvc;
using Citi.Scheduler.Domain;
using Citi.Scheduler.WebUi.Models;

namespace Citi.Scheduler.WebUi.Controllers
{
    public class MachineConfigurationController : ControllerBase<MachineConfigurationModel, MachineConfiguration>
    {
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult Form(int machineId)
        {
            return PartialView(new MachineConfigurationModel
                {
                    MachineId = machineId
                });
        }

        //[OutputCache(NoStore = true, Duration = 1, VaryByParam = "*")]
        public ActionResult Index(int machineId)
        {
            var configs = new MachineConfiguration().SelectAllActive<MachineConfiguration>().Where(x => x.MachineId == machineId);

            return PartialView(new MachineConfigurationModel().CreateModel(configs));
        }

        public ActionResult AddConfiguration(ConfigurationModel model, int machineId)
        {
            var machineConfiguration = new MachineConfiguration().SelectAllActive<MachineConfiguration>()
                                          .FirstOrDefault(x => x.MachineId == machineId && x.ConfigurationId == model.Id);

            if (machineConfiguration == null)
            {
                machineConfiguration = new MachineConfiguration
                    {
                        Active = true,
                        ConfigurationId = model.Id,
                        MachineId = machineId
                    };

                machineConfiguration.Save(machineConfiguration);
            }

            return RedirectToAction("Index", new { machineId });
        }

        public ActionResult Delete(int id)
        {
            var machineId = new MachineConfiguration().SelectById<MachineConfiguration>(id).MachineId;
            DeleteBase(id);
            return RedirectToAction("Index", new { machineId });
        }
    }
}
